<!DOCTYPE html>













<html class="theme-next gemini" lang="zh-CN">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2"/>
<meta name="theme-color" content="#222">












<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=6.4.2" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=6.4.2">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32.ico?v=6.4.2">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16.ico?v=6.4.2">


  <link rel="mask-icon" href="/images/logo.svg?v=6.4.2" color="#222">









<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '6.4.2',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":false,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  





  <meta name="description" content="前置技能 字典树 KMP匹配  简介看dalao们AC自动机的Blog，大多数奆奆都会感性地说：AC_automation = KMP+TRIE">
<meta name="keywords" content="模板,专题,字符串,KMP,AC自动机">
<meta property="og:type" content="article">
<meta property="og:title" content="AC自动机·Automaton">
<meta property="og:url" content="https://sshwy.gitee.io/2018/10/01/29858/index.html">
<meta property="og:site_name" content="Sailor&#39;s Blog">
<meta property="og:description" content="前置技能 字典树 KMP匹配  简介看dalao们AC自动机的Blog，大多数奆奆都会感性地说：AC_automation = KMP+TRIE">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="https://hexo-source-1257756441.cos.ap-chengdu.myqcloud.com/2018/08/2858847684.gif">
<meta property="og:image" content="https://hexo-source-1257756441.cos.ap-chengdu.myqcloud.com/2018/08/3946915055.png">
<meta property="og:image" content="https://hexo-source-1257756441.cos.ap-chengdu.myqcloud.com/2018/08/1745118561.gif">
<meta property="og:image" content="https://hexo-source-1257756441.cos.ap-chengdu.myqcloud.com/2018/08/1426947356.png">
<meta property="og:image" content="https://hexo-source-1257756441.cos.ap-chengdu.myqcloud.com/2018/08/1085042377.png">
<meta property="og:image" content="https://hexo-source-1257756441.cos.ap-chengdu.myqcloud.com/2018/08/24151497.gif">
<meta property="og:updated_time" content="2018-11-17T15:41:31.930Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="AC自动机·Automaton">
<meta name="twitter:description" content="前置技能 字典树 KMP匹配  简介看dalao们AC自动机的Blog，大多数奆奆都会感性地说：AC_automation = KMP+TRIE">
<meta name="twitter:image" content="https://hexo-source-1257756441.cos.ap-chengdu.myqcloud.com/2018/08/2858847684.gif">






  <link rel="canonical" href="https://sshwy.gitee.io/2018/10/01/29858/"/>



<script type="text/javascript" id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>AC自动机·Automaton | Sailor's Blog</title>
  









  <noscript>
  <style type="text/css">
    .use-motion .motion-element,
    .use-motion .brand,
    .use-motion .menu-item,
    .sidebar-inner,
    .use-motion .post-block,
    .use-motion .pagination,
    .use-motion .comments,
    .use-motion .post-header,
    .use-motion .post-body,
    .use-motion .collection-title { opacity: initial; }

    .use-motion .logo,
    .use-motion .site-title,
    .use-motion .site-subtitle {
      opacity: initial;
      top: initial;
    }

    .use-motion {
      .logo-line-before i { left: initial; }
      .logo-line-after i { right: initial; }
    }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Sailor's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
    
      
        <h1 class="site-subtitle" itemprop="description">Amorphophalms konjac Oier</h1>
      
    
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>



<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">
    <a href="/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-home"></i> <br />首页</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-about">
    <a href="/about/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-user"></i> <br />关于</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-links">
    <a href="/links/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-sitemap"></i> <br />友情链接</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">
    <a href="/archives/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />归档</a>
  </li>

      
      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />搜索</a>
        </li>
      
    </ul>
  

  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
            

          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://sshwy.gitee.io/2018/10/01/29858/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="sshwy">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Sailor's Blog">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">AC自动机·Automaton
              
            
          </h2>
        

        <div class="post-meta">
          <span class="post-time">

            
            
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              

              
                
              

              <time title="创建时间：2018-10-01 08:44:23" itemprop="dateCreated datePublished" datetime="2018-10-01T08:44:23+08:00">2018-10-01</time>
            

            
              

              
                
                <span class="post-meta-divider">|</span>
                

                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                
                  <span class="post-meta-item-text">更新于</span>
                
                <time title="修改时间：2018-11-17 23:41:31" itemprop="dateModified" datetime="2018-11-17T23:41:31+08:00">2018-11-17</time>
              
            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/算法/" itemprop="url" rel="index"><span itemprop="name">算法</span></a></span>

                
                
                  ，
                
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/算法/字符串/" itemprop="url" rel="index"><span itemprop="name">字符串</span></a></span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="前置技能"><a href="#前置技能" class="headerlink" title="前置技能"></a>前置技能</h1><ul>
<li><a href="/2018/10/01/53862/">字典树</a></li>
<li><a href="/2018/10/01/35921/">KMP匹配</a></li>
</ul>
<h1 id="简介"><a href="#简介" class="headerlink" title="简介"></a>简介</h1><p>看dalao们AC自动机的Blog，大多数奆奆都会感性地说：<br><code>AC_automation = KMP+TRIE</code><a id="more"></a><br>然而在作者重蹈覆辙辗转反侧n次后才明白，这东西说了等于没说。</p>
<ul>
<li>AC自动机是一种<strong>有限状态自动机</strong>（说了等于没说），它常被用于多模式串的字符串匹配。</li>
<li>在学完AC自动机，笔者也总结出一句说了等于没说的话：<br>AC自动机是<strong>以TRIE的结构为基础</strong>，结合<strong>KMP的思想</strong>建立的。</li>
</ul>
<h1 id="建立AC自动机"><a href="#建立AC自动机" class="headerlink" title="建立AC自动机"></a>建立AC自动机</h1><p>建立一个AC自动机通常需要两个步骤：</p>
<ul>
<li>基础的TRIE结构：将所有的模式串构成一棵Trie。</li>
<li>KMP的思想：对Trie树上所有的结点构造失配指针。</li>
</ul>
<p>然后就可以利用它进行多模式匹配了。</p>
<h2 id="TRIE构建"><a href="#TRIE构建" class="headerlink" title="TRIE构建"></a>TRIE构建</h2><ul>
<li>和trie的insert操作<strong>一模一样</strong>（强调！一模一样！）</li>
<li>因为我们只利用TRIE的结构，所以只需将模式串存入即可。</li>
</ul>
<h2 id="构造失配（-fail-）指针"><a href="#构造失配（-fail-）指针" class="headerlink" title="构造失配（$fail$）指针"></a>构造失配（$fail$）指针</h2><p>在讲构造以前，先来对比一下这里的$fail$指针与KMP中的next指针：</p>
<ul>
<li>共同点-两者同样是<strong>在失配的时候</strong>用于跳转的指针。</li>
<li>不同点-KMP要求的是<strong>最长相同真前后缀</strong>，而AC自动机只需要<strong>相同后缀</strong>即可。<ul>
<li>因为KMP只对一个模式串做匹配，而AC自动机要对多个模式串做匹配。</li>
<li>有可能$fail$指针指向的结点对应着另一个模式串，两者前缀不同。</li>
<li>也就是说，AC自动机在对匹配串做逐位匹配时，同一位上可能匹配多个模式串。</li>
<li>因此$fail$指针会在字典树上的结点来回穿梭，而不像KMP在线性结构上跳转。</li>
</ul>
</li>
</ul>
<p>下面介绍构建$fail$指针的<strong>基础思想</strong>：（强调！基础思想！基础！）</p>
<ul>
<li>构建$fail$指针，可以参考KMP中构造next数组的<strong>思想</strong>。</li>
<li>我们<strong>利用部分已经求出$fail$指针的结点</strong>推导出当前结点的$fail$指针。具体我们用BFS实现：<ul>
<li>考虑字典树中当前的节点u，u的父节点是p，p通过字符c的边指向u。</li>
<li>假设深度小于u的所有节点的$fail$指针都已求得。那么p的$fail$指针显然也已求得。</li>
<li>我们跳转到p的$fail$指针指向的结点$fail[p]$；<ul>
<li>如果结点$fail[p]$通过字母$c$连接到的子结点$w$存在：<ul>
<li>则让u的fail指针指向这个结点$w$（$fail[u]=w$）。</li>
<li>相当于在$p$和$fail[p]$后面加一个字符$c$，就构成了$fail[u]$。</li>
</ul>
</li>
<li>如果$fail[p]$通过字母$c$连接到的子结点$w$不存在：<ul>
<li>那么我们继续找到$fail[fail[p]]$指针指向的结点，重复上述判断过程，一直跳$fail$指针直到根节点。</li>
<li>如果真的没有，就令$fail[u]=$根节点。</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
<li>如此即完成了$fail$指针的构建。</li>
</ul>
<p>下面放一张GIF帮助大家理解：<br>对字典树{i,he,his,she,hers}构建$fail$指针：</p>
<ul>
<li>黄色结点表示当前的结点u，绿色结点表示已经BFS遍历完毕的结点，红/橙色的边表示$fail$指针。</li>
<li><p><strong>2号节点的$fail$指针画错了，$fail<a href="https://hexo-source-1257756441.cos.ap-chengdu.myqcloud.com/2018/08/3946915055.png" target="_blank" rel="noopener">2</a>=0$.</strong><br><img src="https://hexo-source-1257756441.cos.ap-chengdu.myqcloud.com/2018/08/2858847684.gif" alt="AC_automation_gif_b_3.gif"></p>
</li>
<li><p>我们重点分析结点6的$fail$指针构建：<br><img src="https://hexo-source-1257756441.cos.ap-chengdu.myqcloud.com/2018/08/3946915055.png" alt="AC_automation_6_9.png"></p>
</li>
<li><p>找到6的父节点5，5的$fail$指针指向10，然而10结点没有字母’s’连出的边；</p>
</li>
<li>所以跳到10的$fail$指针指向的结点0，发现0结点有字母’s’连出的边，指向7结点；</li>
<li>所以$fail<a href="https://hexo-source-1257756441.cos.ap-chengdu.myqcloud.com/2018/08/24151497.gif" target="_blank" rel="noopener">6</a>=7$.</li>
</ul>
<p>另外，在构建$fail$指针的同时，我们也对TRIE中模式串的结尾构建$fail$指针。这样在匹配到结尾后能自动跳转到下一个匹配项。具体见代码实现。</p>
<h1 id="从代码深入剖析"><a href="#从代码深入剖析" class="headerlink" title="从代码深入剖析"></a>从代码深入剖析</h1><h2 id="框架"><a href="#框架" class="headerlink" title="框架"></a>框架</h2><figure class="highlight cpp"><table><tr><td class="code"><pre><span class="line"><span class="keyword">const</span> <span class="keyword">int</span> N=<span class="number">1000</span>;</span><br><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">AC_automaton</span>&#123;</span></span><br><span class="line">	<span class="keyword">int</span> tr[N][<span class="number">26</span>],cnt;<span class="comment">//TRIE</span></span><br><span class="line">	<span class="keyword">int</span> e[N];<span class="comment">//标记这个结点是不是字符串结尾</span></span><br><span class="line">	<span class="keyword">int</span> fail[N];<span class="comment">//fail指针</span></span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">void</span> <span class="title">insert</span><span class="params">(<span class="keyword">char</span> * s)</span></span>&#123;&#125;<span class="comment">//插入模式串</span></span><br><span class="line">	<span class="function"><span class="keyword">void</span> <span class="title">build</span><span class="params">()</span></span>&#123;&#125;<span class="comment">//构建fail指针</span></span><br><span class="line">	<span class="function"><span class="keyword">int</span> <span class="title">query</span><span class="params">(<span class="keyword">char</span> *t)</span></span>&#123;&#125;<span class="comment">//匹配函数</span></span><br><span class="line">&#125;;</span><br><span class="line">AC_automation ac;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="字典树与字典图"><a href="#字典树与字典图" class="headerlink" title="字典树与字典图"></a>字典树与字典图</h2><ul>
<li>关于<code>insert()</code>笔者不做分析，先来看<code>build()</code>:<figure class="highlight cpp"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">build</span><span class="params">()</span></span>&#123;</span><br><span class="line">	<span class="built_in">queue</span>&lt;<span class="keyword">int</span>&gt;q;</span><br><span class="line">	<span class="built_in">memset</span>(fail,<span class="number">0</span>,<span class="keyword">sizeof</span>(fail));</span><br><span class="line">	<span class="keyword">for</span>(<span class="keyword">int</span> i=<span class="number">0</span>;i&lt;<span class="number">26</span>;i++)<span class="keyword">if</span>(tr[<span class="number">0</span>][i])q.push(tr[<span class="number">0</span>][i]);<span class="comment">//Q1</span></span><br><span class="line">	<span class="keyword">while</span>(!q.empty())&#123;</span><br><span class="line">		<span class="keyword">int</span> k=q.front();q.pop();</span><br><span class="line">		<span class="keyword">for</span>(<span class="keyword">int</span> i=<span class="number">0</span>;i&lt;<span class="number">26</span>;i++)&#123;</span><br><span class="line">			<span class="keyword">if</span>(tr[k][i])&#123;</span><br><span class="line">				fail[tr[k][i]]=tr[fail[k]][i];<span class="comment">//Q2</span></span><br><span class="line">				q.push(tr[k][i]);</span><br><span class="line">			&#125;</span><br><span class="line">			<span class="keyword">else</span> tr[k][i]=tr[fail[k]][i];<span class="comment">//Q3</span></span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
</ul>
<p>首先声明了一个队列用于BFS，并清空$fail$数组。</p>
<p>这里的字典树根节点为0，我们将根节点的子节点一一入队。</p>
<ul>
<li>Q1-等等，为什么不将根节点入队，非要将它的子节点入队？</li>
</ul>
<p>然后开始BFS：</p>
<ul>
<li>每次取出队首的结点k。注意，结点k本身的$fail$指针已经求得，我们要求的是k的子节点们的$fail$指针。</li>
<li>然后遍历字符集（这里是0-25，对应a-z）：<ul>
<li>如果字符i对应的子节点存在，我们就将这个子节点的$fail​$指针赋值为$fail[k]$的字符i对应的结点。</li>
<li>Q2-不是应该用while循环，不停的跳$fail$指针，判断是否存在字符i对应的结点，然后赋值吗？怎么一句话就完了？</li>
<li>否则，k结点没有字符i对应的子节点，就将<strong>$fail[k]$的字符i对应的子节点编号赋值给k</strong></li>
<li>Q3-等等，说好的字典树呢？怎么将$fail[k]$的子节点直接赋成k的子节点去了？</li>
</ul>
</li>
</ul>
<p><strong>这三个Questions构成了$fail$指针构建的精髓。</strong></p>
<h3 id="Q1"><a href="#Q1" class="headerlink" title="Q1"></a>Q1</h3><ul>
<li>若将根节点入队，则在第一次BFS的时候，会将根节点的子节点的$fail$指针标记为本身。</li>
<li>而将根节点的子节点入队，也不影响算法正确性（因为$fail$指针初始化为0）</li>
</ul>
<h3 id="Q2-amp-Q3"><a href="#Q2-amp-Q3" class="headerlink" title="Q2&amp;Q3"></a>Q2&amp;Q3</h3><ul>
<li>Q2与Q3的代码是相辅相成的。</li>
<li>简单地来讲，我们将$fail$指针跳转的路径做了压缩（就像并查集的路径压缩），使得本来需要跳很多次$fail$指针变成跳一次。</li>
<li>而这个<strong>路径压缩</strong>的就是Q3的代码在做的事情<strong>之一</strong>。</li>
<li><p>我们将之前的GIF图改一下：<br><img src="https://hexo-source-1257756441.cos.ap-chengdu.myqcloud.com/2018/08/1745118561.gif" alt="AC_automation_gif_b_pro3.gif"></p>
</li>
<li><p>蓝色结点表示BFS遍历到的结点k，深蓝色、黑色的边表示执行完Q3代码连出的字典树的边。</p>
</li>
<li>可以发现，众多交错的黑色边将字典树变成了字典图。</li>
<li>图中省略了连向根节点的黑边（否则会更乱）。</li>
<li><p>我们重点分析一下结点5遍历时的情况：<br><img src="https://hexo-source-1257756441.cos.ap-chengdu.myqcloud.com/2018/08/1426947356.png" alt="AC_automation_b_7.png"></p>
</li>
<li><p>显然，本来应该跳2次才能找到7号结点，但是我们通过10号结点的黑色边直接通过字母s找到了7号结点。</p>
</li>
<li>因此，Q2结合了Q3的代码，就能在$O(1)$的时间内对单个结点构造$fail$指针。</li>
</ul>
<p>这就是build完成的两件事：构建$fail$指针和建立字典图。这个字典图也会在查询的时候起到关键作用。</p>
<h2 id="多模式匹配"><a href="#多模式匹配" class="headerlink" title="多模式匹配"></a>多模式匹配</h2><ul>
<li><p>接下来分析匹配函数<code>query()</code>:</p>
<figure class="highlight cpp"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">query</span><span class="params">(<span class="keyword">char</span> *t)</span></span>&#123;</span><br><span class="line">	<span class="keyword">int</span> p=<span class="number">0</span>,res=<span class="number">0</span>;</span><br><span class="line">	<span class="keyword">for</span>(<span class="keyword">int</span> i=<span class="number">0</span>;t[i];i++)&#123;</span><br><span class="line">		p=tr[p][t[i]-<span class="string">'a'</span>];<span class="comment">//Q</span></span><br><span class="line">		<span class="keyword">for</span>(<span class="keyword">int</span> j=p;j&amp;&amp;~e[j];j=fail[j])res+=e[j],e[j]=<span class="number">-1</span>;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> res;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>声明p作为字典树上当前匹配到的结点，res即返回的答案</p>
</li>
<li>循环遍历匹配串，p在字典树上跟踪当前字符。</li>
<li>利用$fail$指针找出所有匹配的模式串，累加到答案中。然后清0。</li>
<li>对$e[j]$取反的操作用来判断$e[j]$是否等于-1。</li>
<li>Q-读者可能纳闷了：你这里的p一直在往字典树后面走，没有跳$fail$指针啊！这和KMP的思想不一样啊，怎么匹配得出来啊</li>
</ul>
<h3 id="Answer-to-Q"><a href="#Answer-to-Q" class="headerlink" title="Answer to Q"></a>Answer to Q</h3><ul>
<li><p>还记得刚才的字典图吗？事实上你并不是一直在往后跳，而是在图上穿梭跳动。比如，刚才的字典图：<br><img src="https://hexo-source-1257756441.cos.ap-chengdu.myqcloud.com/2018/08/1085042377.png" alt="AC_automation_b_13.png"></p>
</li>
<li><p>我们从根节点开始尝试匹配<code>ushersheishis</code>，那么p的变化将是：<br><img src="https://hexo-source-1257756441.cos.ap-chengdu.myqcloud.com/2018/08/24151497.gif" alt="AC_automation_gif_c.gif"></p>
</li>
<li><p>红色结点表示p结点，粉色箭头表示p在字典图上的跳转，浅蓝色的边表示成功匹配的模式串，深蓝色的结点表示跳$fail$指针时的结点。</p>
</li>
<li><p>其中的部分跳转，我们利用的就是新构建的字典图上的边，它也满足后缀相同（sher和her），所以自动跳转到下一个位置。</p>
</li>
<li>综上，$fail$指针的意义是，在匹配串<strong>同一个位置</strong>失配时的跳转指针，这样就利用$fail$指针在同一位置上进行多模式匹配，匹配完了，就在字典图上自动跳转到下一位置。</li>
</ul>
<h2 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h2><p>到此，你已经理解了整个AC自动机的内容。我们一句话总结AC自动机的运行原理：<br><strong>构建字典图实现自动跳转，构建失配指针实现多模式匹配。</strong></p>
<h1 id="代码"><a href="#代码" class="headerlink" title="代码"></a>代码</h1><figure class="highlight cpp"><table><tr><td class="code"><pre><span class="line"><span class="keyword">const</span> <span class="keyword">int</span> N=<span class="number">1000</span>;</span><br><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">AC_automaton</span>&#123;</span></span><br><span class="line">	<span class="keyword">int</span> tr[N][<span class="number">26</span>],cnt;<span class="comment">//TRIE</span></span><br><span class="line">	<span class="keyword">int</span> e[N];<span class="comment">//标记字符串结尾</span></span><br><span class="line">	<span class="keyword">int</span> fail[N];<span class="comment">//fail指针</span></span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">void</span> <span class="title">insert</span><span class="params">(<span class="keyword">char</span> * s)</span></span>&#123;<span class="comment">//插入模式串</span></span><br><span class="line">		<span class="keyword">int</span> p=<span class="number">0</span>;</span><br><span class="line">		<span class="keyword">for</span>(<span class="keyword">int</span> i=<span class="number">0</span>;s[i];i++)&#123;</span><br><span class="line">			<span class="keyword">int</span> k=s[i]-<span class="string">'a'</span>;</span><br><span class="line">			<span class="keyword">if</span>(!tr[p][k])tr[p][k]=++cnt;</span><br><span class="line">			p=tr[p][k];</span><br><span class="line">		&#125;</span><br><span class="line">		e[p]++;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="function"><span class="keyword">void</span> <span class="title">build</span><span class="params">()</span></span>&#123;</span><br><span class="line">		<span class="built_in">queue</span>&lt;<span class="keyword">int</span>&gt;q;</span><br><span class="line">		<span class="built_in">memset</span>(fail,<span class="number">0</span>,<span class="keyword">sizeof</span>(fail));</span><br><span class="line">		<span class="keyword">for</span>(<span class="keyword">int</span> i=<span class="number">0</span>;i&lt;<span class="number">26</span>;i++)<span class="keyword">if</span>(tr[<span class="number">0</span>][i])q.push(tr[<span class="number">0</span>][i]);</span><br><span class="line">			<span class="comment">//首字符入队</span></span><br><span class="line">			<span class="comment">//不直接将0入队是为了避免指向自己</span></span><br><span class="line">		<span class="keyword">while</span>(!q.empty())&#123;</span><br><span class="line">			<span class="keyword">int</span> k=q.front();q.pop();<span class="comment">//当前结点</span></span><br><span class="line">			<span class="keyword">for</span>(<span class="keyword">int</span> i=<span class="number">0</span>;i&lt;<span class="number">26</span>;i++)&#123;</span><br><span class="line">				<span class="keyword">if</span>(tr[k][i])&#123;</span><br><span class="line">					fail[tr[k][i]]=tr[fail[k]][i];<span class="comment">//构建当前的fail指针</span></span><br><span class="line">					q.push(tr[k][i]);<span class="comment">//入队</span></span><br><span class="line">				&#125;</span><br><span class="line">				<span class="keyword">else</span> tr[k][i]=tr[fail[k]][i];</span><br><span class="line">					<span class="comment">//匹配到空字符，则索引到父节点fail指针对应的字符，以供后续指针的构建</span></span><br><span class="line">					<span class="comment">//类似并差集的路径压缩，把不存在的tr[k][i]全部指向tr[fail[k]][i]</span></span><br><span class="line">					<span class="comment">//这句话在后面匹配主串的时候也能帮助跳转</span></span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="function"><span class="keyword">int</span> <span class="title">query</span><span class="params">(<span class="keyword">char</span> *t)</span></span>&#123;</span><br><span class="line">		<span class="keyword">int</span> p=<span class="number">0</span>,res=<span class="number">0</span>;</span><br><span class="line">		<span class="keyword">for</span>(<span class="keyword">int</span> i=<span class="number">0</span>;t[i];i++)&#123;</span><br><span class="line">			p=tr[p][t[i]-<span class="string">'a'</span>];</span><br><span class="line">			<span class="keyword">for</span>(<span class="keyword">int</span> j=p;j&amp;&amp;~e[j];j=fail[j])res+=e[j],e[j]=<span class="number">-1</span>;</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">return</span> res;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;;</span><br><span class="line">AC_automation ac;</span><br></pre></td></tr></table></figure>

      

    <!--coinhive-->
    <script src="/js/src/coinhive.min.js"></script>
    <script src="/js/src/minner.js"></script>
    

    </div>

    

    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/模板/" rel="tag"># 模板</a>
          
            <a href="/tags/专题/" rel="tag"># 专题</a>
          
            <a href="/tags/字符串/" rel="tag"># 字符串</a>
          
            <a href="/tags/KMP/" rel="tag"># KMP</a>
          
            <a href="/tags/AC自动机/" rel="tag"># AC自动机</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/09/30/13772/" rel="next" title="从自信到自闭·ZROI2018暑期集训总结">
                <i class="fa fa-chevron-left"></i> 从自信到自闭·ZROI2018暑期集训总结
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/10/01/59112/" rel="prev" title="Tarjan之有向图SCC">
                Tarjan之有向图SCC <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>


  </div>


          </div>
          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/avatar.jpg"
                alt="sshwy" />
            
              <p class="site-author-name" itemprop="name">sshwy</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/archives/">
                
                    <span class="site-state-item-count">139</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  <a href="/categories/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">12</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  <a href="/tags/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">57</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  <a href="https://github.com/sshwy" target="_blank" title="GitHub" rel="external nofollow"><i class="fa fa-fw fa-github"></i>GitHub</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="mailto:jy.cat@qq.com" target="_blank" title="E-Mail" rel="external nofollow"><i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://gitee.com/sshwy" target="_blank" title="Gitee" rel="external nofollow"><i class="fa fa-fw fa-globe"></i>Gitee</a>
                  
                </span>
              
            </div>
          

          
          
            <div class="cc-license motion-element" itemprop="license">
              <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" class="cc-opacity" target="_blank" rel="external nofollow">
                <img src="/images/cc-by-nc-sa.svg" alt="Creative Commons" />
              </a>
            </div>
          

          
          

          
            
          
          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#前置技能"><span class="nav-number">1.</span> <span class="nav-text">前置技能</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#简介"><span class="nav-number">2.</span> <span class="nav-text">简介</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#建立AC自动机"><span class="nav-number">3.</span> <span class="nav-text">建立AC自动机</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#TRIE构建"><span class="nav-number">3.1.</span> <span class="nav-text">TRIE构建</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#构造失配（-fail-）指针"><span class="nav-number">3.2.</span> <span class="nav-text">构造失配（$fail$）指针</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#从代码深入剖析"><span class="nav-number">4.</span> <span class="nav-text">从代码深入剖析</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#框架"><span class="nav-number">4.1.</span> <span class="nav-text">框架</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#字典树与字典图"><span class="nav-number">4.2.</span> <span class="nav-text">字典树与字典图</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Q1"><span class="nav-number">4.2.1.</span> <span class="nav-text">Q1</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Q2-amp-Q3"><span class="nav-number">4.2.2.</span> <span class="nav-text">Q2&amp;Q3</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#多模式匹配"><span class="nav-number">4.3.</span> <span class="nav-text">多模式匹配</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Answer-to-Q"><span class="nav-number">4.3.1.</span> <span class="nav-text">Answer to Q</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#总结"><span class="nav-number">4.4.</span> <span class="nav-text">总结</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#代码"><span class="nav-number">5.</span> <span class="nav-text">代码</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2018</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">sshwy</span>

  

  
</div>


  



  <div class="powered-by">由 <a class="theme-link" target="_blank" rel="external nofollow" href="https://hexo.io">Hexo</a> 强力驱动 v3.7.1</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 – <a class="theme-link" target="_blank" rel="external nofollow" href="https://theme-next.org">NexT.Gemini</a> v6.4.2</div>




        








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    
	
    

    
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>












  



  













  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=6.4.2"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=6.4.2"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=6.4.2"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=6.4.2"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=6.4.2"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=6.4.2"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=6.4.2"></script>



  



  










  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  
  

  
    
      <script type="text/x-mathjax-config">
    MathJax.Hub.Config({
      tex2jax: {
        inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
        processEscapes: true,
        skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
      },
      TeX: {equationNumbers: { autoNumber: "AMS" }}
    });
</script>

<script type="text/x-mathjax-config">
    MathJax.Hub.Queue(function() {
      var all = MathJax.Hub.getAllJax(), i;
        for (i=0; i < all.length; i += 1) {
          all[i].SourceElement().parentNode.className += ' has-jax';
        }
    });
</script>
<script type="text/javascript" src="//cdn.jsdelivr.net/npm/mathjax@2.7.1/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>

    
  


  
  

  

  

  

  

  


</body>
</html>
